<template>
  <div class="AddOrUpdate_main add_container column_two">
    <div ref="approve_content" class="main_main">
      <!-- 审批规则 -->
      <div class="formItem_header1">
        <div>审批规则</div>
        <div class="approvalRemark">
          如果有多个审批人时：
        </div>
        <el-radio-group v-model="formData.signWay" :disabled="true">
          <el-radio label="0">或签  &nbsp;  (其中一名审批人同意即可)</el-radio>
          <el-radio label="1">会签  &nbsp;(所有审批人均同意)</el-radio>
        </el-radio-group>
        <div class="approvalRemark">
          同级审批中存在多个审批人时：
        </div>
        <el-radio-group v-model="formData.signOrder" :disabled="true">
          <el-radio label="0">普通审批 &nbsp; (无先后顺序)</el-radio>
          <el-radio label="1">依次审批 &nbsp; (根据选择排列审批顺序)</el-radio>
        </el-radio-group>
        <div class="approvalRemark">
          如果没有找到审批人时：将转交给企业管理员重新分配
        </div>
      </div>
      <!-- 审批流程 -->
      <div class="approveProcess">
        <div>审批流程</div>

        <!-- 审批列表 -->
        <div v-for=" (item,index) in approveData" :key="index">
          <!-- 一级审批 -->
          <div class="appro_floor_content">
            <div>
              <!-- <i class="el-icon-circle-plus-outline" /> -->
              <svg-icon style="height:25px;width:25px" icon-class="审批" />
            </div>
            <div class="appro_floor"><span style="margin-right:15px"> {{ item.approvelevel }}</span></div>
          </div>

          <!--  添加审批人-->
          <div class="approvePerson">
            <!-- <div class="addApprovePerson" @click="addAapprovePerson(index)">
              <i class="el-icon-circle-plus-outline addapprove_person_icon" />
              <span class="add_person_text">添加审批人</span>
            </div>
            <div class="approve_border" /> -->

            <!-- 审批人列表 -->
            <div :id="'dropId'+index" class="approve_list approve_person_list">
              <div v-for="(item2,index2) in item.approvalUsers" :key="index2" class="approve_person_list">
                <div class="approve_person_content">
                  <div class="approve_person_img">
                    <el-avatar v-if="item2.avatarUrl" :src="item2.avatarUrl" icon="el-icon-user-solid" class="icon_user" />
                    <el-avatar v-else class="icon_user" :src="avatarImg" />
                    <!-- <div class="svg_error" @click="deleteApproveperson(index,index2)">
                      <svg-icon icon-class="驳回" />
                    </div> -->
                  </div>
                  <div class="company_name">{{ item2.realName||'' }}</div>
                  <div class="option_name">{{ item2.deptName||'' }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 添加审批层级 -->
        <!-- <div class="appro_floor_content">
          <div @click="addApproveLevel"><i class="el-icon-circle-plus-outline" /></div>
          <div class="addappro_floor"><span>添加审批层级</span></div>
        </div> -->
      </div>

    </div>
    <!-- <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div> -->
  </div>
</template>

<script>
import avatarImg from '@/assets/images/avatar/容器@3x.png'
import { addOrUpdate, getInfo } from '@/api/system/approvalSettings'
import { list } from '@/api/system/user'
import ChooseUser from './seachUser.vue'
import Sortable from 'sortablejs'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      avatarImg: avatarImg,
      radio: 3,
      radio1: 3,
      formData: {
        id: '',
        code: '',
        signOrder: '0',
        signWay: '0',
        details: []
      },
      options: [
        { value: '1', label: '驳回一级' },
        { value: '2', label: '驳回全部' }
      ],
      signWay: '0',
      signOrder: '0',
      approveData: [], // 审批人列表
      falg: true, // 审批人校验
      messageText: '',
      peopleList: [],
      tableHeight: '250',
      userOptions: [],
      equipmentList: [],
      selectionsAll1: [],
      ids: [],
      newData: [],
      roleOptions: [],
      selectionsAll: [], // 表格所有页选中的行
      inx: 1,
      tableData: [],
      listData: [],
      rules: {
        code: [
          { required: true, message: '审批表单不能为空', trigger: 'blur' }
        ],
        reject: [
          { required: true, message: '驳回类型不能为空', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    approveData: {
      handler: function() {
        this.newData = JSON.parse(JSON.stringify(this.approveData))
      },
      deep: true,
      immediate: true
    }

  },
  created() {
    if (!this.id) { // 没有id就是新增
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.getUserList()
  },
  methods: {
    rowDrop(index) {
      console.log(index)
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('#dropId' + index)
      const _this = this
      Sortable.create(tbody, {
        onEnd({ oldIndex, newIndex }) {
          var newArr = JSON.parse(JSON.stringify(_this.approveData[index].approvalUsers))
          const cacheData1 = _this.$deepClone(newArr[oldIndex])
          const cacheData2 = _this.$deepClone(newArr[newIndex])
          const cacheTableData = _this.$deepClone(newArr)
          cacheTableData[newIndex] = cacheData1
          cacheTableData[oldIndex] = cacheData2
          newArr = []
          _this.newData[index].approvalUsers = []
          setTimeout(() => { // 加延时重置表格
            newArr = cacheTableData
            _this.newData[index].approvalUsers = newArr
          }, 20)
        }
      })
    },
    addAapprovePerson(index) {
      console.log(index)
      this.$layer.iframe({// 弹框
        content: {
          content: ChooseUser, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            deptIndex: index,
            selectedRow: this.approveData[index].approvalUsers
          }// props
        },
        area: ['1000px', '700px'],
        title: '选择人员', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    peopleChoose(data, index) {
      console.log(index)
      this.approveData[index].approvalUsers = data
      console.log(this.approveData)
    },
    headerCellClassName(data) {
      if (['userId'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    // 新增审批层级
    addApproveLevel() {
      const approvelevel = this.intToChinese(this.approveData.length + 1)
      const approvalUsers = {
        approvelevel: `${approvelevel}级审批`,
        approvalUsers: []
      }
      this.approveData.push(approvalUsers)
      this.$nextTick(() => {
        const scrollEl = this.$refs.approve_content
        scrollEl.scrollTo({ top: scrollEl.scrollHeight, behavior: 'smooth' })
      })
      this.$nextTick(() => {
        this.rowDrop(this.approveData.length - 1)
      })
    },
    // 删除审批人
    deleteApproveperson(index, index2) {
      this.approveData[index].approvalUsers.splice(index2, 1)
    },
    intToChinese(str) {
      str = str + ''
      const len = str.length - 1
      var idxs = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿']
      var num = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
      return str.replace(/([1-9]|0+)/g, function($, $1, idx, full) {
        var pos = 0
        if ($1[0] != '0') {
          pos = len - idx
          if (idx == 0 && $1[0] == 1 && idxs[len - idx] == '十') {
            return idxs[len - idx]
          }
          return num[$1[0]] + idxs[len - idx]
        } else {
          var left = len - idx
          var right = len - idx + $1.length
          if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
            pos = left - left % 4
          }
          if (pos) {
            return idxs[pos] + num[$1[0]]
          } else if (idx + $1.length >= len) {
            return ''
          } else {
            return num[$1[0]]
          }
        }
      })
    },
    getUserList() {
      list({ status: '1' }).then(res => {
        this.peopleList = res.data
        console.log(res)
      })
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        // Object.keys(this.formData).forEach(key => { // 给右边数据赋值
        //   this.formData[key] = res.data[key]
        // })
        this.formData = res.data
        for (let i = 0; i < res.data.details.length; i++) {
          res.data.details[i].approvelevel = this.intToChinese(i + 1) + '级审批'
        }
        this.approveData = res.data.details
        this.newData = JSON.parse(JSON.stringify(this.approveData))
        // this.$nextTick(() => {
        //   console.log(this.approveData)
        //   for (let i = 0; i < this.approveData.length; i++) {
        //     this.$nextTick(() => {
        //       this.rowDrop(i)
        //     })
        //   }
        // })
      })
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
    },
    deleteAudit(index) {
      this.approveData.splice(index, 1)
      this.approveData.forEach((ele, index3) => {
        ele.approvelevel = this.intToChinese(index3 + 1) + '级审批'
      })
      console.log(this.approveData)
    },
    add() {
      this.tableData.push({ deptName: '', userId: '' })
    },
    onSubmit() {
      this.approveData.map((item, index) => {
        if (item.approvalUsers.length == 0) {
          this.falg = false
          this.messageText = `${this.approveData[index].approvelevel}未选择审批人`
        } else {
          this.falg = true
        }
      })
      if (this.falg) {
        this.approveData = JSON.parse(JSON.stringify(this.newData))
        this.approveData.forEach((ele, index) => {
          ele.userId = ele.approvalUsers.map(item => item.userId).toString()
          ele.taskNo = index + 1
        })
        this.formData.details = this.approveData
        addOrUpdate(this.formData).then(res => {
          this.$message.success(res.msg)
          this.cancel()
        })
      } else {
        this.$message.error(this.messageText)
        return
      }
      // console.log(111)
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner {
    border-color: #1890ff;
    background: #1890ff;
}
/deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
     background-color: white;
}
// .approvalRemark::before{
//   content: "*";
//   color: #ff4949;
// }
// .appro_floor::before{
//   content: "*";
//   color: #ff4949;
// }
.main_main{
  padding-top:10px ;
}
.approveProcess{
    font-size: 18px;
    margin-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom:20px ;
}
.formItem_header1{
    font-size: 18px;
    width: 100%;
    line-height: 40px;
    padding-left: 20px;
    padding-right: 20px;
    .approvalRemark{
      font-size: 14px;
      color: #333333;
    }
}
.appro_floor_content{
  height: 26px;
display: flex;
margin-top: 10px;
.appro_floor{
  padding-left: 15px;
  .delete_button{
    display: inline-block;
    color: #f56c6c;
    background: #fef0f0;
    border-color: #fbc4c4;
    border: 1px solid;
    border-radius: 4px;
    font-size: 14px;
    padding: 0px 10px;
    cursor: default;
  }
}
}
/deep/.el-icon-circle-plus-outline{
  font-size: 26px;
      color: #387BFD;

}
.approve_person_list{
  display: flex;
  flex-flow:row wrap;
}
.approve_person_content{
  text-align: center;
  width: 100px;
  margin-bottom: 10px;
}
.approve_person_img{
  position: relative;
  margin: 0 auto;
  width: 50px;
  height: 50px;
}
.icon_user{
  font-size: 40px;
  width: 50px;
  height: 50px;
}
.svg_error{
  position: absolute;
  right: -5px;
  top: -5px;
}
.approve_border{
  height: 50px;
  border-right: 1px solid #dfe6ec;;
}
.approvePerson{
  padding-left: 20px;
  margin-top :10px;
  margin-left: 12px;
  display: flex;
  border-left:1px solid  rgb(32,126,249);
  height: 100%;
  min-height: 100px;
}
.addApprovePerson{
  display: flex;
  width: 100px;
  cursor: default;

  flex-direction:column;
  text-align: center;
  .addapprove_person_icon{
    color: #387BFD;
    font-size: 50px;
    height: 50px !important;
  }
}
.inco_xing{
  color: #FF3B30;
}
.addappro_floor{
  padding-left: 15px;
  color: #6B6A6F !important;
}
.add_person_text, .company_name  {
  font-size: 14px ;
  color: #6B6A6F !important;
  margin: 5px 0;
      width: 100px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.option_name{
  font-size: 14px ;
  color: #9899A1;
        width: 100px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
/deep/.el-radio{
  width: 300px;
  color: #333333;
}
/deep/.el-radio-group{
  margin-left: 10px;
  margin-bottom: 10px;
}
/deep/.el-radio__input.is-checked + .el-radio__label {
  color: #333333 !important;
}
</style>
